package dfl.bysj.service.impl;

import dfl.bysj.config.RedisKey;
import dfl.bysj.entity.Advice;
import dfl.bysj.entity.AdviceVO;
import dfl.bysj.mapper.AdviceMapper;
import dfl.bysj.service.AdviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author DFL
 * @since 2022-04-26
 */
@Slf4j
@Service
public class AdviceServiceImpl extends ServiceImpl<AdviceMapper, Advice> implements AdviceService {

    private RedisTemplate redisTemplate;

    private AdviceMapper adviceMapper;

    @Autowired
    public void setAdviceMapper(AdviceMapper adviceMapper) {
        this.adviceMapper = adviceMapper;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private List<Advice> advices;

    private AtomicReference<Advice> adviceAtomicReference= new AtomicReference<>(new Advice());




    private void getAdvices(){
        advices= (List<Advice>) redisTemplate.opsForValue().get(RedisKey.ALL_ADVICE);
        if (advices==null){
            updateRedisOfAdvices();

        }
    }

    private void updateRedisOfAdvices(){
        advices=list();
        redisTemplate.opsForValue().set(RedisKey.ALL_ADVICE,advices,7, TimeUnit.DAYS);
    }

    @Override
    public List<AdviceVO> getAllAdvicesFormatTime() {
        getAdvices();
        ArrayList<AdviceVO> adviceVOS=new ArrayList<>();
        DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        log.info(advices.toString());
        advices.stream().forEach(s->{
            AdviceVO adviceVO=new AdviceVO(
                    s.getAdvId(),
                    s.getAdvTitle(),
                    s.getAdvComment(),
                    s.getAdmId(),
                     s.getCreateTime().format(dateTimeFormatter),
                    s.getUpdateTime().format(dateTimeFormatter));
            adviceVOS.add(adviceVO);
        });
        return adviceVOS;
    }

    @Override
    public void insertAdvice(Advice advice) {
        advice.setAdmId(1);
        adviceMapper.insert(advice);
        updateRedisOfAdvices();
    }

    @Override
    public void updateAdvice(Advice advice) {
        log.info(advice.toString());
        adviceMapper.updateById(advice);
        updateRedisOfAdvices();
    }

    @Override
    public void deleteAdvice(String advId) {
        adviceMapper.deleteById(Integer.parseInt(advId));
        updateRedisOfAdvices();
    }
}
